package proxy.myjdkproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @auther: Steven
 * @created： 2018/2/7 22:40
 * Description：产品经理
 */
public class Product implements InvocationHandler {
    // get coder
    private Coder coder;
    public boolean isHaveIdleCoder() {
        return haveIdleCoder;
    }

    public void setHaveIdleCoder(boolean haveIdleCoder) {
        this.haveIdleCoder = haveIdleCoder;
    }

    private boolean haveIdleCoder;

    public Object getInstance() {
        haveIdleCoder=true;
        System.out.println("客户您好，我是产品经理，正在核查是否有员工能处理您的问题");
        // 判断是否有空闲程序猿
        if (!haveIdleCoder) {
            System.out.println("现在没有人手，没法儿接需求。抱歉");
            return null;
        }
        System.out.println("哎呦，竟然有人闲着！");
        System.out.println("----内部沟通----交由某猿开始处理需求");
        this.coder = new Coder();
        Class cl = coder.getClass();
        // 获取新建coder的代理权
        Object proxy = Proxy.newProxyInstance(cl.getClassLoader(), cl.getInterfaces(), this);
        return proxy;
    }

    public Object getInstance(Coder coder) {
        this.coder = coder;
        Class cl = coder.getClass();
        return Proxy.newProxyInstance(cl.getClassLoader(), cl.getInterfaces(), this);
    }

    /**
     * 实现需求
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("---内部沟通----"+this.coder.getName()+"即将处理你的需求");
        Object result = method.invoke(this.coder, args);
        System.out.println("客户您好，您的需求已经完成了，请您验收");
        return result;
    }
}
